package com.example.demoshiro.common.shiro;

import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfigure {

    private final CustomSessionDao customSessionDao;

    public ShiroConfigure(CustomSessionDao customSessionDao) {
        this.customSessionDao = customSessionDao;
    }

    @Bean
    public SessionManager sessionManager() {
        CustomSessionManager sessionManager = new CustomSessionManager();
        sessionManager.setSessionDAO(customSessionDao);
//        // 设置会话过期时间
//        sessionManager.setGlobalSessionTimeout(3 * 60 * 1000);  // 默认半小时
//        sessionManager.setDeleteInvalidSessions(true);
//        // 设置会话定时检查
//        sessionManager.setSessionValidationInterval(180000);    // 默认一小时
//        sessionManager.setSessionValidationSchedulerEnabled(true);
        return sessionManager;
    }

    @Bean
    public CustomRealm customRealm() {
        return new CustomRealm();
    }

    @Bean
    public DefaultWebSecurityManager getSecurityManagerBean(@Qualifier("customRealm") CustomRealm customRealm) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setSessionManager(sessionManager());
        securityManager.setRealm(customRealm);
        return securityManager;
    }

    @Bean(name = "filterFactoryBean")
    public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("getSecurityManagerBean") DefaultWebSecurityManager securityManager) {

        ShiroFilterFactoryBean filterFactoryBean = new ShiroFilterFactoryBean();
        filterFactoryBean.setSecurityManager(securityManager);
//        Map<String, Filter> filterMap = new  LinkedHashMap<>();
//        filterMap.put("auth",new AuthFilter());
//        filterFactoryBean.setFilters(filterMap);
        Map<String, String> map = new LinkedHashMap<>();
        map.put("/test1", "authc");
        map.put("/test2", "perms[user:add]");
        filterFactoryBean.setFilterChainDefinitionMap(map);
        // 登录拦截
        filterFactoryBean.setLoginUrl("/login");
//        filterFactoryBean.setLoginUrl("http://127.0.0.1:8808/html/index.html");

        return filterFactoryBean;
    }
}
